﻿using DevelopAssistant.Service.TemplatingEngine;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DevelopAssistant.Service
{
    internal class Creater
    {
        internal static string CreateCode(TextTemplatingEngine host, string csType, string templateFile, string savePath,
         string outType, out string message)
        {
            message = string.Empty;

            host.TemplateFile = templateFile;
            Microsoft.VisualStudio.TextTemplating.Engine engine = new Microsoft.VisualStudio.TextTemplating.Engine();

            string input = "";
            string output = "";            

            try
            {
                if (!System.IO.File.Exists(host.TemplateFile))
                {
                    throw new Exception("未找到 " + host.TemplateFile + " 模板文件");
                }

                input = System.IO.File.ReadAllText(host.TemplateFile);
                output = engine.ProcessTemplate(input, host);               

                if (outType == "File")
                {
                    try
                    {
                        string outputFile = savePath + host.ClassName + host.FileExtension;
                        if (System.IO.Directory.Exists(savePath))
                        {
                            System.IO.File.WriteAllText(outputFile, output);
                        }
                        else
                        {
                            System.IO.Directory.CreateDirectory(savePath);
                            System.IO.File.WriteAllText(outputFile, output);
                        }
                    }
                    catch (Exception error)
                    {
                        DevelopAssistant.Common.NLogger.WriteToLine(error.Message, "错误", DateTime.Now, error.Source, error.StackTrace);
                        message += error.ToString() + "\r\n";
                    }
                }

                message += host.ClassName + " " + csType + " 代码生成成功" + "\r\n";

                foreach (CompilerError error in host.Errors)
                {
                    message += error.ToString() + "\r\n";
                }
            }
            catch (Exception ex)
            {
                DevelopAssistant.Common.NLogger.WriteToLine(ex.Message, "错误", DateTime.Now, ex.Source, ex.StackTrace);
            }

            return output;
        }
    }
}
